<?php
namespace hdphp\wx;
/**
* 微信处理类
*/
class Wx
{
	protected $message;

	public function __construct()
	{
		$this->message=$this->getMessage();
	}

	/**
	 * 获得微信服务器发送过来的消息
	 * @return   [type]                   [description]
	 */
	public function getMessage()
	{
		if (isset($GLOBALS['HTTP_RAW_POST_DATA'])) {
			$post = $GLOBALS['HTTP_RAW_POST_DATA'];
			return simplexml_load_string( $post, 'SimpleXMLElement', LIBXML_NOCDATA );
		}
	}


	protected function accessToken($name='access_token')
	{
		if (!$access_token=Cache::get($name)) {
			$appid=c('wx.appid');
			$appsecret=c('wx.appsecret');
			$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
			$d=Curl::get($url);
			$d=json_decode($d,true);
			$access_token=$d['access_token'];
			Cache::set($name,$access_token,3600);
		}
		return $access_token;

	}


	/**
	 * 绑定微信服务器
	 * @return   [type]                   [description]
	 */
	public function bind()
	{
		if (
			isset( $_GET["signature"] )
		    && isset( $_GET["timestamp"] )
		    && isset( $_GET["nonce"] )
		    && isset( $_GET["echostr"] )
		    ) {
			$signature = $_GET["signature"];
			$timestamp = $_GET["timestamp"];
			$nonce = $_GET["nonce"];
			$token = c("wx.token");
			$tmpArr = array($token, $timestamp, $nonce);
			sort($tmpArr, SORT_STRING);
			$tmpStr = implode( $tmpArr );
			$tmpStr = sha1( $tmpStr );
			if( $tmpStr == $signature ){
				die($_GET["echostr"]);
			}else{
				return false;
			}
		}
	}


	public function instance($name)
	{
		static $cache=[];
		if (!isset($cache[$name])) {
			$class = '\hdphp\wx\build\\' . ucfirst($name);
			$cache[$name] = new $class;
		}
		return $cache[$name];
	}

}